package com.qf.events.listeners;

import com.qf.enums.DeviceStatus;
import com.qf.events.DevicePowerEvent;
import com.qf.pojo.SysDevice;
import com.qf.service.SysDeviceService;
import com.qf.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * created by 赵文韬 on 2022/3/26 20:49
 */
@Component
public class DevicePowerListenner {
   private SysDeviceService sysDeviceService;
    @Autowired
    public void setSysDeviceService(SysDeviceService sysDeviceService) {
        this.sysDeviceService = sysDeviceService;
    }

    @EventListener
    @Async
    public void onEvent(DevicePowerEvent event){
        String ip = event.getIp();
        String deviceId = event.getDeviceId();
        DeviceStatus deviceStatus = event.getDeviceStatus();
        //获取地区
        String location = RequestUtil.getLocationByIp(ip);
        SysDevice sysDevice = new SysDevice();
        sysDevice.setDeviceId(deviceId);
        switch (deviceStatus){
            case ONLINE:
                sysDevice.setBindTime(new Date());
                sysDevice.setConnectLocation(location);
                sysDevice.setIsOnline(1L);
                sysDevice.setCurrentConnectIp(ip);
                break;
            case OFFLINE:
                sysDevice.setIsOnline(2L);
                sysDevice.setLostConnectTime(new Date());
                break;

        }
        sysDeviceService.updateDevice(sysDevice);
    }
}
